package com.buka.service.impl;

import com.buka.domain.ResponseResult;
import com.buka.service.UploadService;
import com.buka.util.PathUtils;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class UploadServiceImpl implements UploadService {

    /**
     * 头像上传接口
     */
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //创建新的文件名字
        String filePath = PathUtils.generateFilePath(originalFilename);
        //如果判断通过上传文件到OSS  获取外链地址
        String url = uploadOss(img, filePath);
        return ResponseResult.okResult(url);
    }

    @Value("${ak}")
    private String accessKey;
    @Value("${sk}")
    private String secretKey;
    @Value("${addr}")
    private String bucket;
    @Value("${qiniuurl}")
    private String qiniuurl;

    private String uploadOss(MultipartFile imgFile, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return qiniuurl + key;
        } catch (Exception ex) {
            throw new RuntimeException("上传失败");
        }
    }

}
